package com.base.thread;

import java.util.concurrent.*;

/**
 * 创建线程类的第三种方式1——通过实现Callable接口，再通过FutureTask类进行包装
 *
 * @author innocent
 * @date 2019/1/17 17:03
 */
public class CallableThread implements Callable {
    //线程共享资源
    private int i;

    @Override
    public Object call() throws Exception {
        while (i < 500) {
            i ++;
            System.out.println(Thread.currentThread().getName() +"\t" + i);
        }

        return "hello callable";
    }

    public static void main(String[] args) {
        CallableThread c1 = new CallableThread();
        CallableThread c2 = new CallableThread();
        CallableThread c3 = new CallableThread();

        //通过调用get()方法，在线程执行完成后，可以接收，线程方法返回值
        FutureTask<String> f1 = new FutureTask(c1);
        FutureTask<String> f2 = new FutureTask(c2);
        FutureTask<String> f3 = new FutureTask(c3);

        Thread t1 = new Thread(f1);
        t1.setName("线程1");
        Thread t2 = new Thread(f2);
        t2.setName("线程2");
        Thread t3 = new Thread(f3);
        t3.setName("线程3");

        //开启线程
        t1.start();
        t2.start();
        t3.start();

        //接收线程方法返回值
        try {
            String s1 = f1.get();
            String s2 = f2.get();
            String s3 = f3.get();

            System.out.println("s1 = " + s1);
            System.out.println("s2 = " + s2);
            System.out.println("s3 = " + s3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


    }
}
